﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using NetDon.OA.Business;
using NetDon.OA.Interface;
using NetDon.Utilities;


namespace NetDon.OA.Portal
{
    internal class DictionaryDataSourceView : DataSourceView
    {
        private readonly DictionaryDataSource _owner;

        public DictionaryDataSourceView(DictionaryDataSource owner, string viewName)
            : base(owner, viewName)
        {
            _owner = owner;
        }

        public override bool CanPage
        {
            get { return true; }
        }

        public override bool CanRetrieveTotalRowCount
        {
            get { return true; }
        }

        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments)
        {
            arguments.RaiseUnsupportedCapabilitiesError(this);
            if (!string.IsNullOrEmpty(_owner.CategoryName))
            {
                var service = ServiceContainer.GetService<IDictionaryService>();
                var context = ServiceContainer.GetService<ApplicationContext>() as OApplicationContext;
                IEnumerable<DictionaryData> entries = service.GetDataItems(_owner.CategoryName, context.CompanyId);
                var arrayList = new ArrayList();
                if (entries != null)
                {
                    if (arguments.RetrieveTotalRowCount)
                    {
                        arguments.TotalRowCount = entries.Count();
                    }
                    if (CanPage && arguments.MaximumRows > 0 && arguments.StartRowIndex >= 0)
                    {
                        entries = entries.Skip(arguments.StartRowIndex).Take(arguments.MaximumRows);
                    }
                    arrayList.AddRange(entries.ToArray());
                }
                string description = EnumUtilities.GetDescription(_owner.EmptyItemType);
                if (!string.IsNullOrEmpty(description))
                {
                    arrayList.Insert(0, new
                                            {
                                                Value = string.Empty,
                                                Name = description
                                            });
                }
                return arrayList;
            }
            return null;
        }

    }
}
